// TestsDataTable.tsx
import type { Test } from "@server/src/schemas/tests";
import type { Table as TTable } from "@tanstack/react-table";
import { flexRender } from "@tanstack/react-table";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { useSelectedTestStore } from "@/stores/useSelectedTestStore";
import { TestsColumns } from "./tests-columns";

interface Props {
  table: TTable<Test>;
}

export function TestsDataTable({ table }: Props) {
  const selectTest = useSelectedTestStore((s) => s.selectTest);

  return (
    <Table className="h-full w-full">
      <TableHeader className="sticky top-0 z-10 bg-background">
        {table.getHeaderGroups().map((g) => (
          <TableRow
            key={g.id}
            className="bg-muted/20 *:border-border [&>:not(:last-child)]:border-r"
          >
            {g.headers.map((h) => (
              <TableHead key={h.id} className="h-min p-2 text-sm">
                {h.isPlaceholder ? null : flexRender(h.column.columnDef.header, h.getContext())}
              </TableHead>
            ))}
          </TableRow>
        ))}
      </TableHeader>

      <TableBody className="[&_tr:last-child]:border-b-0 [&_tr]:border-b">
        {table.getRowModel().rows.length ? (
          table.getRowModel().rows.map((row) => (
            <TableRow
              key={row.id}
              data-state={row.getIsSelected() ? "selected" : undefined}
              onClick={() => selectTest(row.original)}
              className="*:border-border [&>:not(:last-child)]:border-r"
            >
              {row.getVisibleCells().map((cell) => (
                <TableCell key={cell.id} className="truncate px-2 py-1.5 text-sm">
                  {flexRender(cell.column.columnDef.cell, cell.getContext())}
                </TableCell>
              ))}
            </TableRow>
          ))
        ) : (
          <TableRow>
            <TableCell colSpan={TestsColumns.length} className="h-full text-center text-xs">
              No results.
            </TableCell>
          </TableRow>
        )}
      </TableBody>
    </Table>
  );
}
